package org.example.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.function.BiConsumer;

@Service
@Slf4j
public class AsyncService {

    private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    @Async
    public void doInBackground(BiConsumer<Void, Throwable> done) {
        tap();
        log.info("do something");
        sleep();
        log.info("done");
        done.accept(null, null);
    }

    private void tap() {
        int a = threadLocal.get() == null ? 0 : threadLocal.get();
        int b = a + 1;
        threadLocal.set(b);
        log.info("threadLocal: {} -> {}", a, b);
    }

    private static void sleep() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ignored) {
        }
    }
}
